package role

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
	"time"
)

type roleRepository struct {
	tenant_db.TenantDB
}

// NewRoleRepository 构造函数
func NewRoleRepository() RoleRepositoryIface {
	return &roleRepository{}
}

// RoleSave 新增/更新角色
func (r *roleRepository) RoleSave(ctx context.Context, role *GfyRolePo) (int64, error) {
	if role.Id != 0 {
		err := r.GetTenantDB(ctx).Table(GfyRolePo{}.TableName()).
			Where("id = ?", role.Id).
			Limit(1).
			Updates(map[string]interface{}{
				"name":        role.Name,
				"modified_on": role.ModifiedOn,
				"modified_by": role.ModifiedBy,
			}).Error
		if err != nil {
			return 0, err
		}

		return role.Id, nil
	}

	err := r.GetTenantDB(ctx).Save(role).Error
	if err != nil {
		return 0, err
	}

	return role.Id, nil
}

// DeleteRole 删除角色
func (r *roleRepository) DeleteRole(ctx context.Context, roleId int64, operatorId int64) (int64, error) {
	err := r.GetTenantDB(ctx).Table(GfyRolePo{}.TableName()).
		Where("id = ?", roleId).
		Limit(1).
		Updates(map[string]interface{}{
			"is_deleted":  constants.IsDeletedTrue,
			"modified_by": operatorId,
			"modified_on": time.Now(),
		}).Error
	return roleId, err
}

// RoleList 角色列表
func (r *roleRepository) RoleList(ctx context.Context) ([]*GfyRolePo, error) {
	list := make([]*GfyRolePo, 0)
	err := r.GetTenantDB(ctx).Where("is_deleted = ?", constants.IsDeletedFalse).Find(&list).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

// RoleDetail 获取角色详情
func (r *roleRepository) RoleDetail(ctx context.Context, roleId int64) (*GfyRolePo, error) {
	var role = &GfyRolePo{}
	err := r.GetTenantDB(ctx).
		Where("id = ? and is_deleted = ?", roleId, constants.IsDeletedFalse).
		First(role).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return role, nil
}

// AddPermissionToRole 增加权限到角色
func (r *roleRepository) AddPermissionToRole(ctx context.Context, roleId int64, permissionIds []int64) error {
	db := r.GetTenantDB(ctx).Begin()

	// 1. 删除之前的记录
	err := db.Table(GfyxRolePermissionRelation{}.TableName()).
		Where("role_id = ?", roleId).
		Updates(map[string]interface{}{
			"is_deleted":  constants.IsDeletedTrue,
			"modified_on": time.Now(),
			"modified_by": "",
		}).Error
	if err != nil {
		db.Rollback()
		return err
	}

	for _, pIds := range permissionIds {
		rolePer := &GfyxRolePermissionRelation{
			RoleId:       roleId,
			PermissionId: pIds,
			CreatedOn:    time.Now(),
			CreatedBy:    "",
			ModifiedOn:   time.Now(),
			ModifiedBy:   "",
		}
		err := db.Save(rolePer).Error
		if err != nil {
			db.Rollback()
			return err
		}
	}

	db.Commit()
	return nil
}

// PermissionListByRoleId 获取角色关联的的权限列表
func (r *roleRepository) PermissionListByRoleId(ctx context.Context, roleId int64) ([]*GfyxRolePermissionRelation, error) {
	list := make([]*GfyxRolePermissionRelation, 0)
	err := r.GetTenantDB(ctx).
		Where("is_deleted = ? and role_id = ?", constants.IsDeletedFalse, roleId).
		Find(&list).Error
	return list, err
}

// GetByRoleName 检查角色名称是否存在
func (r *roleRepository) GetByRoleName(ctx context.Context, name string) (*GfyRolePo, error) {
	role := &GfyRolePo{}
	err := r.GetTenantDB(ctx).Where("name = ? and is_deleted = ?", name, constants.IsDeletedFalse).First(role).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return role, nil
}

// RoleListByRoleIds 根据角色编号角色列表
func (r *roleRepository) RoleListByRoleIds(ctx context.Context, roleIds []int64) ([]*GfyRolePo, error) {
	list := make([]*GfyRolePo, 0)
	err := r.GetTenantDB(ctx).
		Where("is_deleted = ? and id in (?)", constants.IsDeletedFalse, roleIds).
		Find(&list).Error
	return list, err
}
